<template>
	<i v-if="isShowIconSvg" class="el-icon" :style="setIconSvgStyle" :title="props.title">
		<component :is="getIconName" />
	</i>
	<div v-else-if="isShowIconImg" :style="setIconImgOutStyle">
		<img :src="getIconName" :style="setIconSvgInsStyle" :title="props.title" />
	</div>
	<i v-else :class="getIconName" :style="setIconSvgStyle" :title="props.title"></i>
</template>

<script setup lang="ts" name="icon">
import { computed } from "vue";

// 定义父组件传过来的值
interface IconProps {
	name: string; // 图标名称
	size?: number; // 图标大小
	color?: string; // 图标颜色
	title?: string; // 提示文本
}
const props = withDefaults(defineProps<IconProps>(), {
	size: 14,
	color: "",
	title: "",
});

// 在线链接、本地引入地址前缀
const linesString = ["https", "http", "/src", "/assets", "data:image", import.meta.env.VITE_PUBLIC_PATH];

// 获取 icon 图标名称
const getIconName = computed(() => {
	return props.name;
});
// 用于判断 element plus 自带图标的显示、隐藏
const isShowIconSvg = computed(() => {
	return props.name ? props.name.startsWith("ele-") : false;
});
// 用于判断在线链接、本地引入等图标显示、隐藏
const isShowIconImg = computed(() => {
	return props.name ? linesString.find(str => props.name.startsWith(str)) : false;
});
// 设置图标样式
const setIconSvgStyle = computed(() => {
	return `font-size: ${props.size}px !important;color: ${props.color};`;
});
// 设置图片样式
const setIconImgOutStyle = computed(() => {
	return `width: ${props.size}px;height: ${props.size}px;display: inline-block;overflow: hidden;`;
});
// 设置图片样式
const setIconSvgInsStyle = computed(() => {
	const baseStyle = `width: ${props.size}px;height: ${props.size}px;`;
	if (props.color) {
		const filterStyle: string[] = [];
		const compatibles: string[] = ["-webkit", "-ms", "-o", "-moz"];
		compatibles.forEach(j => filterStyle.push(`${j}-filter: drop-shadow(${props.color} 30px 0);`));
		return baseStyle + `position: relative;left: -${props.size}px;${filterStyle.join("")}`;
	} else {
		return baseStyle;
	}
});
</script>
